﻿using AutoMapper;
using MediatR;
using ProductionManagement.Application.Command.ProductionPlanCommand;
using ProductionManagement.Domain.ProductionDomain;
using ProductionManagement.Infrstructre.lnterface;
using SqlSugar;

namespace ProductionManagement.Application.CommandHandler.ProductionPlanCommandHandler
{
    /// <summary>
    /// 修改生产计划命令处理器
    /// </summary>
    public class ProductionPlanUpdCommandHandler:IRequestHandler<ProductionPlanUpdCommand,int>
    {
        private readonly IProductionPlanRepository _productionPlanRep;
        private readonly IProductionProductRepository _productionProductRep;
        private readonly ISqlSugarClient db;
        private readonly IMapper _mapper;

        public ProductionPlanUpdCommandHandler(IProductionPlanRepository productionPlanRep, IProductionProductRepository productionProductRep, ISqlSugarClient db, IMapper mapper)
        {
            this._productionPlanRep = productionPlanRep;
            this._productionProductRep = productionProductRep;
            this.db = db;
            this._mapper = mapper;
        }

        public async Task<int> Handle(ProductionPlanUpdCommand request, CancellationToken cancellationToken)
        {
            // 开启事务
            db.Ado.BeginTran();
            try
            {
                //修改生产计划
                var se = await db.Queryable<ProductionPlan>()
                                 .Where(c => c.ProductionPlansId == request.upddto.ProductionPlansId)
                .FirstAsync();

                var preProduction = _mapper.Map<ProductionPlan>(request.upddto);
                int Item = await _productionPlanRep.UpdAsync(preProduction);


                //删除生成计划产品中的数据
                var itemsToDelete = await db.Queryable<ProductionProduct>()
                                  .Where(c => c.PPDocumentNumber == se.PPDocumentNumber)
                                  .ToListAsync();
                foreach (var item in itemsToDelete)
                {
                    await _productionProductRep.DelRange(new List<ProductionProduct> { item });
                }


                foreach (var subpiece in request.upddto.UpdDto)
                {
                    ProductionProduct items = new ProductionProduct();
                    items.ProductionProductId = subpiece.ProductionProductId;
                    items.PPDocumentNumber = preProduction.PPDocumentNumber;
                    items.ProductId = subpiece.ProductId;
                    items.PNumber = subpiece.PNumber;
                    items.PName = subpiece.PName;
                    items.PSpec = subpiece.PSpec;
                    items.PUnit = subpiece.PUnit;
                    items.PPNum = subpiece.PPNum;
                    items.MSubject = subpiece.MSubject;
                    items.PPAppStartDate = subpiece.PPAppStartDate;
                    items.PPAppEndDate = subpiece.PPAppEndDate;
                    items.PPReleDate = subpiece.PPReleDate;
                    items.PProuctSmark = subpiece.PProuctSmark;
                    items.AddName = preProduction.AddName;
                    items.AddTime = preProduction.AddTime;
                    items.UpdName = preProduction.UpdName;
                    items.UpdTime = preProduction.UpdTime;
                    items.Office_Id = preProduction.Office_Id;
                    items.User_Id = preProduction.User_Id;
                    await _productionProductRep.AddAsync(items);
                }
                // 提交事务
                db.Ado.CommitTran();
                return 1;
            }
            catch (Exception ex)
            {
                // 捕获异常并回滚事务
                db.Ado.RollbackTran();
                // 可以记录日志以便调试
                throw new Exception("事务失败，已回滚所有操作", ex);
            }
        }
    }
}
